import dayjs from 'dayjs';
export class HttpError extends Error {
  public statusCode: number;
  public details?: any;

  constructor(message: string, statusCode: number = 500, details?: any) {
    super(message);
    this.name = 'HttpError';
    this.statusCode = statusCode;
    this.details = details;
    // 保持正确的原型链
    Object.setPrototypeOf(this, HttpError.prototype);
  }

  // 预定义的错误类型
  //  400 Bad Request 请求格式错误（如 JSON 语法错、缺少必传参数）
  static badRequest(message: string = 'Bad Request', details?: any) {
    return new HttpError(message, 400, details);
  }
  //  401 Unauthorized
  static unauthorized(message: string = 'Unauthorized') {
    return new HttpError(message, 401);
  }
  //  403 Forbidden
  static forbidden(message: string = 'Forbidden') {
    return new HttpError(message, 403);
  }
  //  404 Not Found
  static notFound(message: string = 'Not Found') {
    return new HttpError(message, 404);
  }

  //  409 Conflict 与当前资源状态冲突（如重复创建唯一资源）
  static conflict(message: string = 'Conflict') {
    return new HttpError(message, 409);
  }
  //  422 Unprocessable Entity 格式正确，但语义/业务规则不满足
  static unprocessableEntity(message: string = 'Unprocessable Entity', details?: any) {
    return new HttpError(message, 422, details);
  }

  //  500 Internal Server Error 务器在处理请求时遇到了意外情况，无法完成请
  static internalServerError(message: string = 'Internal Server Error') {
    return new HttpError(message, 500);
  }

  // 转换为响应格式
  toJSON() {
    return {
      error: this.name,
      message: this.message,
      code: this.statusCode,
      data: this.details,
      timestamp: dayjs().format('YYYY年MM月DD日 HH:mm:ss'),
    };
  }
}

export default HttpError;